# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution:
    def maxAncestorDiff(self, root: TreeNode) -> int:
        def func(node, ans):
            if node is None:
                return (2**31, -2**31)
            if node.left is None and node.right is None:
                return (node.val, node.val)
            minLeft, maxLeft = func(node.left, ans)
            minRight, maxRight = func(node.right, ans)
            minVal = min(minLeft, minRight)
            maxVal = max(maxLeft, maxRight)
            res = max(abs(node.val - minVal), abs(node.val - maxVal))
            ans[0] = max(res, ans[0])
            minVal = min(node.val, minVal)
            maxVal = max(node.val, maxVal)

            return (minVal, maxVal)

        ans = [0]
        func(root, ans)

        return ans[0]
